package com.springmvc.netty.client.websocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.springmvc.netty.server.websocket.WebSocketChannelInitializer;
import com.springmvc.netty.server.websocket.WebSocketServer;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class WebSocketClient {

	private static final Logger	LOGGER = LoggerFactory.getLogger(WebSocketClient.class);

	private static final int	port   = 8989;

	public static void main(String[] args) throws InterruptedException, IOException {
		EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(eventLoopGroup);
			bootstrap.channel(NioSocketChannel.class);
			bootstrap.handler(new LoggingHandler(LogLevel.INFO));
			bootstrap.handler(new ClientInitializer());
			
//			serverBootstrap.childHandler(new WebSocketChannelInitializer());

			Channel channel = bootstrap.connect("localhost", port).sync().channel();

			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
			for (;;) {
				channel.writeAndFlush(new TextWebSocketFrame("---》TextWebSocketFrame"));
				channel.writeAndFlush(reader.readLine() + "\n");
			}
		} finally {
			eventLoopGroup.shutdownGracefully(); //优雅关闭
		}

	}

	public void clientStart() {
		LOGGER.info("开始启动websocket...");
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(bossGroup, workerGroup);
			serverBootstrap.channel(NioServerSocketChannel.class);
			serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
			serverBootstrap.childHandler(new WebSocketChannelInitializer());

			ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
			channelFuture.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
		LOGGER.info("完成启动websocket...");
	}
}